package com.sgq.vue.controller.system;


import com.sgq.vue.entity.system.Department;
import com.sgq.vue.result.Result;
import com.sgq.vue.service.system.DepartmentService;
import com.sgq.vue.utils.system.DepartmentTree;
import com.sgq.vue.vo.query.DepartmentQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author SGQ
 * @since 2023-10-30
 */
@RestController
@RequestMapping("/api/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    /**
     *  查询部门列表
     * @param departmentQueryVo
     * @return
     */
    @GetMapping("/list")
    public Result list(DepartmentQueryVo departmentQueryVo){


        List<Department> departmentList = departmentService.findDepartmentList(departmentQueryVo);

        List<Department> departments = DepartmentTree.makeDepartmentTree(departmentList, 0L);

        return Result.ok(departments);

    }

    /**
     *  查询部门列表
     * @param
     * @return
     */
    @GetMapping("/parent/list")
    public Result getParentDepartment(){

        List<Department> parentDepartment = departmentService.findParentDepartment();

        return Result.ok(parentDepartment);

    }

    /**
     *  新增
     * @param
     * @return
     */
    @PostMapping ("/add")
    @PreAuthorize("hasAnyAuthority('sys:department:add')")
    public Result add(@RequestBody Department department){

        boolean save = departmentService.save(department);

        if (save){
            return Result.ok().message("添加成功");
        }
        return Result.ok().message("添加失败");

    }


    /**
     *  修改
     * @param
     * @return
     */
    @PutMapping("/update")
    @PreAuthorize("hasAnyAuthority('sys:department:edit')")
    public Result update(@RequestBody Department department){

        boolean update = departmentService.updateById(department);

        if (update){
            return Result.ok().message("修改成功");
        }
        return Result.ok().message("修改失败");

    }

    /**
     *  修改
     * @param
     * @return
     */
    @PreAuthorize("hasAnyAuthority('sys:department:delete')")
    @DeleteMapping ("/delete/{id}")
    public Result remove(@PathVariable("id") Long id){

        boolean update = departmentService.removeById(id);

        if (update){
            return Result.ok().message("删除成功");
        }
        return Result.ok().message("删除失败");

    }

    /**
     *  修改
     * @param
     * @return
     */
    @GetMapping ("/check/{id}")
    @PreAuthorize("hasAnyAuthority('sys:department:delete')")
    public Result check(@PathVariable("id") Long id){

        boolean check = departmentService.check(id);

        return check == true ?  Result.exist().message("该部门存在子部门") :  Result.ok();

    }

}

